<template>
  <lay-layer
    title="新增菜单权限"
    v-model="visible"
    :shade="true"
    :shadeClose="false"
    :shadeOpacity="0.3"
    :maxmin="true"
    :area="['350px']"
    :teleportDisabled="false"
    :btn="actionBtn"
  >
    <Loading :loading="isLoading">
      <lay-form :model="formState" ref="formRef" size="xs" style="width: 88%">
        <lay-form-item label="所属菜单：">
          <lay-input :modelValue="info.name" :disabled="true" allow-clear />
        </lay-form-item>

        <lay-form-item label="所属路径：">
          <lay-input :modelValue="info.path" :disabled="true" allow-clear />
        </lay-form-item>

        <lay-form-item label="权限名称：" prop="name" required>
          <lay-input
            type="text"
            v-model="formState.name"
            placeholder="例如：新增"
            allow-clear
          />
        </lay-form-item>

        <lay-form-item label="权限标识：" prop="action_mark" required>
          <lay-input
            type="text"
            v-model="formState.action_mark"
            placeholder="例如：add"
            allow-clear
          />
        </lay-form-item>

        <lay-form-item label="排序：" prop="sort" required>
          <lay-input-number v-model="formState.sort" placeholder="排序值" />
        </lay-form-item>
      </lay-form>
    </Loading>
  </lay-layer>
</template>
<script setup>
import { ref, nextTick } from "vue";
import { msgSuccess, msgError } from "@/utils/message";
import { deepCopy } from "@/utils/tool";
import * as Api from "@/api/menu/index";
// 定义抛出的事件名称
const emit = defineEmits(["callback"]);
// 定义动态数据
const isLoading = ref(false);
const formRef = ref(undefined);
// 定义表单信息，deepCopy解决指针问题
const formData = {
  name: "",
  type: 20,
  action_mark: "",
  pid: 0,
  sort: 100,
};
const formState = ref({});
const visible = ref(false);
const actionBtn = ref([
  {
    text: "提交",
    callback: () => {
      handleSubmit();
    },
  },
  {
    text: "取消",
    callback: () => {
      visible.value = false;
    },
  },
]);
const info = ref({});

// 控制显示
const show = (item) => {
  info.value = item;
  visible.value = true;
  //初始化表单信息
  nextTick(() => {
    formRef.value.reset();
    formState.value = deepCopy(formData);
  });
};

// 提交
const handleSubmit = () => {
  if (formState.value.name == "" || formState.value.name == null) {
    return msgError("权限名称不能为空");
  }
  if (formState.value.action_mark == "" || formState.value.action_mark == null) {
    return msgError("权限标识不能为空");
  }
  if (formState.value.sort == "") {
    return msgError("排序值必填");
  }

  formState.value.pid = info.value.menu_id;

  isLoading.value = true;
  Api.add({ form: formState.value })
    .then((result) => {
      if (result.status == 200) {
        msgSuccess(result.message);
        visible.value = false;
      } else {
        msgError(result.message);
      }
    })
    .finally(() => {
      emit("callback", "");
      isLoading.value = false;
    });
};

// 导出方法/属性给父组件
defineExpose({ show });
</script>
